const Service = require("egg").Service;
const rules = {
  rolename: {
    type: "string",
    required: false,
    desc: "角色名称"
  },
  desc: {
    type: "string",
    required: false,
    desc: "角色描述"
  }
};

class RoleService extends Service {
  // 查找角色名称
  async findByRoleName(rolename) {
    const { app } = this;
    const res = await app.model.Role.findOne({
      where: {
        rolename
      }
    });
    return res;
  }
  // 添加角色
  async addRole(rolename, desc = "") {
    const { app, ctx } = this;
    // 当前用户名
    const creator = ctx.tokenUser.username;
    const res = await app.model.Role.create({
      rolename,
      desc,
      creator
    });
    return res;
  }
  // 删除角色
  async delRoleInfo(id) {
    const { app, ctx } = this;
    const currentUser = ctx.tokenUser;
    ctx.validate({
      id: {
        type: "number",
        required: true,
        desc: "角色id"
      }
    });
    const role = await app.model.Role.findOne({
      where: {
        id,
        creator: currentUser.username
      }
    });
    if (!role) {
      ctx.throw(401, "角色不存在或不是当前创建用户");
    }
    const res = await role.destroy();
    return res;
  }
  // 编辑角色
  async editRoleInfo(rolename, desc, memberId) {
    const { app, ctx } = this;
    const id = +ctx.params.id;
    const currentUser = ctx.tokenUser;
    ctx.validate({
      id: {
        type: "number",
        required: true,
        desc: "角色id"
      },
      ...rules
    });
    const role = await app.model.Role.findOne({
      where: {
        id,
        creator: currentUser.username
      }
    });
    if (!role) {
      ctx.throw(401, "角色不存在或不是当前创建用户");
    }
    const res = await role.update({
      rolename,
      desc,
      memberId
    });
    return res;
  }
  // 模糊查询列表角色
  async findNameOrCreatorList(rolename, creator) {
    const { ctx, app } = this;
    const { Op } = app.Sequelize;
    let pageBean = ctx.query.pageBean;
    // 数据查询
    const where = {};
    if (rolename !== undefined) {
      where.rolename = {
        [Op.like]: `%${rolename}%`
      };
    }
    if (creator !== undefined) {
      where.creator = {
        [Op.like]: `%${creator}%`
      };
    }
    const res = await app.model.Role.findAndCountAll({
      where,
      offset: pageBean
        ? (pageBean.pageIndex - 1) * pageBean.pageSize
        : undefined,
      limit: pageBean ? parseInt(pageBean.pageSize) : undefined
    });
    return res;
  }
}

module.exports = RoleService;
